package com.bbx.taxi.client.Activity.Menu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.Bind;

import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.sdk.model.base.BaseRequest;
import com.bbx.api.sdk.model.passanger.Coupon;
import com.bbx.api.sdk.model.passanger.Return.Coupon.CouponList;
import com.bbx.api.sdk.model.passanger.Return.Coupon.Coupons;
import com.bbx.api.sdk.model.passanger.Return.Coupon.Metadata;
import com.bbx.api.sdk.model.passanger.Return.Coupon.Recommen.RecommenUsers;
import com.bbx.api.sdk.model.passanger.Return.Coupon.Recommen.Users;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.sdk.net.passeger.conn.CouponNet;
import com.bbx.api.sdk.net.passeger.conn.CouponRecommendNet;
import com.bbx.taxi.client.Task.BaseAsyncTask;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Adapter.CouponAdapter;
import com.bbx.taxi.client.Bean.Extra.RecommenMsg;
import com.bbx.taxi.client.DB.CouponDB;
import com.bbx.taxi.client.DB.RecommenDB;
import com.example.mylistview.pullListView.PullToRefreshLayout;
import com.example.mylistview.pullListView.PullToRefreshLayout.OnRefreshListener;
import com.example.mylistview.pullListView.PullableListView;
import com.example.mylistview.pullListView.PullableListView.OnLoadListener;
import com.example.mylistview.swipemenu.MyListView;

/**
 * 推荐有奖的具体内容
 * 
 */
public class RecommenContentActivity extends BaseBBXActivity implements OnLoadListener,OnRefreshListener{
	@Bind(R.id.MyListView)
	MyListView mMyListView;
	@Bind(R.id.pullToRefreshLayout)
	PullToRefreshLayout pullToRefreshLayout;
	@Bind(R.id.tv_count)TextView tv_count;
	@Bind(R.id.layout_list)LinearLayout layout_list;
	@Bind(R.id.layout_nodata)LinearLayout layout_nodata;
	@Bind(R.id.layout_get)LinearLayout layout_get;
	@Bind(R.id.tv_totalsum)TextView tv_totalsum;
	@Bind(R.id.tv_notes)TextView tv_notes;
	private MyAdapter mMyAdapter;
	private RecommenTask mRecommenTask;
	private RecommenDB db_recommen;// 推荐数据库
	private List<Users> list = new ArrayList<Users>();
	private Handler handler = new Handler();
    private int num=10;
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_recommen_content);
		super.onCreate(savedInstanceState);
		
		
	}

	@Override
	protected void initView() {
		setTitle(getString(R.string.recommen_award));
		db_recommen = new RecommenDB();
		initMyListView();
		list = new ArrayList<Users>();
		mMyAdapter = new MyAdapter(this, list);
		mMyListView.setAdapter(mMyAdapter);
		mMyListView.hideLoad();
		/////////////////////
		Bundle bundle = getIntent().getExtras();
		if(bundle!=null){
			if(bundle.getString(RecommenMsg.totalsum)!=null){
				tv_totalsum.setText(String.format(getString(R.string.share_totalsum), bundle.getString(RecommenMsg.totalsum)));
			}
			if(bundle.getString(RecommenMsg.totalcnt)!=null){
				tv_count.setText(String.format(getString(R.string.share_count),bundle.getString(RecommenMsg.totalcnt)));
			}
		}
	}

	@Override
	protected void initData() {
		onReadDB();

	}
	/**
	 * 刚进来的时候读取的
	 */
	private void onReadDB() {
		list.clear();
		list.addAll(db_recommen.onReadDB(-1, num));
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				notifyDataSetChanged(mMyAdapter);
				refresh(); // 主动下拉刷新所有的订单
			}
		}, 200);
	}
	private void initMyListView() {
		pullToRefreshLayout.setOnRefreshListener(this);
	    mMyListView.setOnLoadListener(this);
	    mMyListView.setHasMoreData(false);
	}
	private void refresh() {
//		start_id = "0";
		getRecommen(0);
	}

	private void load() {
		getRecommen(1);
	}
	/**
	 * 获取推荐列表
	 */
	public void getRecommen(int type){
		BaseRequest mBaseRequest = new BaseRequest(context);
		mBaseRequest.uid = mApplication.getUid();
		mBaseRequest.access_token = mApplication.getToken();
		mRecommenTask = new RecommenTask(context, mBaseRequest, type);
		mRecommenTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}
	private class RecommenTask extends BaseAsyncTask {

		private BaseRequest mBaseRequest;
		private int type;// 0为刷新，1为加载

		public RecommenTask(Activity context, BaseRequest mBaseRequest, int type) {
			super(context);
			this.mBaseRequest = mBaseRequest;
			setIsReturnString(true);
			setType(type);
		}

		@Override
		public void onSuccess(int status,Object object) {
			if(object!=null){
				RecommenUsers mRecommenUsers=new RecommenUsers();
				JSONArray ja_users;
				try {
					JSONObject json = new JSONObject((String) object);
					ja_users = json.getJSONArray("users");
					List<Users> users_list = new ArrayList<Users>();
					for (int i = 0; i < ja_users.length(); i++) {
						Users users = new Users();
						JSONObject jo = new JSONObject(ja_users.get(i).toString());
						users.setPhone(jo.getString("phone"));
						users.setState(jo.getString("state"));
						if(!jo.isNull("headimg"))
						users.setHeadimg(jo.getString("headimg"));
						//0为注册，则过滤
						if(!jo.getString("state").equals("0")){
							users_list.add(users);
						}
					
					}
					mRecommenUsers.setList(users_list);
				} catch (JSONException e) {
					e.printStackTrace();
				}	
				if (getType() == 0) {// 刷新
					list.clear();
					if (mRecommenUsers.getList()!= null
							&& !mRecommenUsers.getList().isEmpty()) {
						list.addAll(mRecommenUsers.getList());
						db_recommen.onDelete();
						db_recommen.onWriteDB(list);
						if (mRecommenUsers.getList().size() >= num) {
							mMyListView.setHasMoreData(true);
						}else{
							mMyListView.setHasMoreData(false);
						}
					}
					else {
						db_recommen.onDelete();
					}
					pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
					notifyDataSetChanged(mMyAdapter);
				}
				else{//加载
				}
			}
		}

		@Override
		public void onFailed(int status, String msg) {
			
		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			String json = new JsonBuild().setModel(mBaseRequest).getJson();
			return new CouponRecommendNet(context, json);
		}

	}
	
	public class MyAdapter extends BaseAdapter {
		private List<Users> list;
		private Context main;

		public MyAdapter(Context context, List<Users> list) {
			this.list = list;
			main = context;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewholder;
			if (convertView == null) {
				LayoutInflater inflater = LayoutInflater.from(main);
				convertView = (View) inflater.inflate(
						R.layout.item_recommen_content, null);
				viewholder = new ViewHolder();
				viewholder.name = (TextView) convertView
						.findViewById(R.id.tv_name);
				viewholder.tel = (TextView) convertView
						.findViewById(R.id.tv_tel);
				convertView.setTag(viewholder);
			} else
				viewholder = (ViewHolder) convertView.getTag();
//			viewholder.name.setText(list.get(position).get("name"));
			viewholder.tel.setText(list.get(position).getPhone());
			return convertView;

		}

		public class ViewHolder {
			TextView name, tel;
		}
	}
	public void notifyDataSetChanged(BaseAdapter adapter){
		adapter.notifyDataSetChanged();
		onisShowNodata(adapter);
	}
	public void onisShowNodata(BaseAdapter adapter){
		if(adapter.getCount()==0){
			layout_nodata.setVisibility(View.VISIBLE);
			layout_list.setVisibility(View.GONE);
			layout_get.setVisibility(View.GONE);
			tv_notes.setVisibility(View.GONE);
		}
		else{
			layout_get.setVisibility(View.VISIBLE);
			layout_nodata.setVisibility(View.GONE);
			layout_list.setVisibility(View.VISIBLE);
			tv_notes.setVisibility(View.VISIBLE);
		}
	}
	@Override
	protected void onDestroy() {
		if (mRecommenTask != null
				&& mRecommenTask.getStatus() != AsyncTask.Status.FINISHED)
			mRecommenTask.cancel(true);
		super.onDestroy();
	}

	@Override
	public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
		refresh();
	}

	@Override
	public void onLoad(PullableListView pullableListView) {
		load();
	}
}
